 //
//  DAHomePageViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/26.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAHomePageViewController.h"
#import "DABackBookTableViewCell.h"
#import "DABorrowBookTableViewCell.h"
#import "DASystemNotificationTableViewCell.h"
#import "DABackBookModel.h"
#import "DABorrowBookModel.h"
#import "DASystemNotificationModel.h"
#import "DASearchBookViewController.h"
#import "DAHomePageShowBookDetailViewController.h"
#import "DASearchBookDetailViewController.h"
#import "DABookTypeViewController.h"
#import "DAHomePageTimeLineModel.h"
#import "DAPersonalViewController.h"
#import "DAOtherPersonalViewController.h"
#import "DAUserListViewController.h"
#import "FLAnimatedImage.h"
#import "DAInputCommentView.h"
#import "DALikeAndComment.h"
#import "DACommentButton.h"
#import "DAPopLikeAndCommentView.h"
#import "DACommentView.h"
#import "DAReplyModel.h"
#import "DAFileUploadTableViewCell.h"
#import "DAWebFileViewController.h"

@interface DAHomePageViewController ()<UITableViewDataSource, UITableViewDelegate, showBookDetail, borrowBookShowDetail, DAFileUploadTableViewCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) DABackBookModel *backModel;
@property (nonatomic, strong) DABorrowBookModel *borrowModel;
@property (nonatomic, strong) DASystemNotificationModel *systemModel;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *righeItem;
/** 灰色蒙版*/
@property (nonatomic, strong) UIView *grayView;
@property (nonatomic, strong) DAHomePageShowBookDetailViewController *detailView;
@property (nonatomic, strong) NSMutableArray *dataArray;
// 记录page
@property (nonatomic, assign) NSInteger pageCount;
@property (nonatomic, strong) NSMutableArray *loadMoreDataArray;
@property (nonatomic) BOOL isRefresh;
@property (nonatomic) BOOL isDataSuccessful;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *footer;
@property (nonatomic, strong) DABackBookTableViewCell *backCell;
@property (nonatomic, strong) DABorrowBookTableViewCell *borrowCell;
// 保存评论的数组
@property (nonatomic, strong) NSMutableArray *commentArray;
// 输入评论框
@property (nonatomic, strong) DAInputCommentView *inputCommentView;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) DAPopLikeAndCommentView *popView;
@property (nonatomic, strong) NSIndexPath *selectIndexPath;
// 判断是评论还是回复的
@property (nonatomic, assign) BOOL isSelectComment;
// 用来接收传过来的回复者id
@property (nonatomic, copy) NSString *replyUserID;
@property (nonatomic, copy) NSString *replyToUserName;
@property (nonatomic, strong) NSMutableDictionary *replyDic;
@property (nonatomic, strong) NSString *userName;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) NSMutableArray *rowsArray;
@property (nonatomic, copy) NSString *replyTimeLine;
@property (nonatomic, strong) NSIndexPath *cellIndexPath;
@property (nonatomic, strong) NSMutableArray *borrowCommentArray;
// 用于view 的移动, 使评论框落在cell 下面
@property (nonatomic, assign) CGFloat replyViewDrawFloat;
@property (nonatomic, assign) BOOL isFlag;
@property (nonatomic, assign) CGFloat replyToOtherFloat;
@property (nonatomic, assign) NSInteger isBackCellTag;
@property (nonatomic, assign) CGFloat replyHeight;
@property (nonatomic, assign) CGFloat commentTableViewCellRowHeight;
@property (nonatomic, assign) BOOL isKeyboardFirstShow;

@property (nonatomic, assign) CGRect isFirstRiseFrame;
@property (nonatomic, assign) CGPoint currentTableViewPoint;
@property (nonatomic, assign) BOOL isShowingKeyboard;

@end

@implementation DAHomePageViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [SVProgressHUD dismiss];
    self.navigationController.navigationBarHidden = NO;
    [self setNotification];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 页面将要消失的时候 让输入框失去第一响应者
    [self.inputCommentView.sendTextView resignFirstResponder];
}
// 注册通知 用于借书成功后,通知首页刷新数据
- (void)setNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pageRefresh) name:@"isBorrowSuccessful" object:nil];
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(grayViewHidden) name:@"GRAYVIEWHIDDEN" object:nil];
    // 注册通知 监听键盘弹起
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InputCommentViewKeyboardRise:) name:UIKeyboardWillShowNotification object:nil];
    // 监听键盘收回
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InputCommentViewKeyboardHidden:) name:UIKeyboardWillHideNotification object:nil];
//    //监听键盘高度变化
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
    // 点击阅读过此书的人的通知
   // [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sendMessageToOtherPersonal:) name:@"SendMessageToOtherPersonal" object:nil];
}

#pragma mark - 点击阅读过的人触发的方法
- (void)sendMessageToOtherPersonal:(NSNotification *)not{
    NSLog(@"objext== %@", not.object);
    
    self.detailView.view.hidden = YES;
    [self.grayView removeFromSuperview];
    [self turnPersonal:not.object];
}
#pragma mark - 借阅成功后触发的方法 通知刷新
- (void)pageRefresh{
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark - 移除通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"isBorrowSuccessful" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"VIEWHIDDEN" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GRAYVIEWHIDDEN" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"SendMessageToOtherPersonal" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ClickCommentView" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"REPLYCOMMENT" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"transferReplyID" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"REPLYCOMMENTUPDATE" object:nil];
    NSLog(@"__delloc");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //[self.tableView.mj_header beginRefreshing];
    /** 调用导航栏设置 */
   // self.commentArray = [@[]mutableCopy];
    self.isFlag = NO;
    [self ConfigurationNavigation];
    /** 调用准备数据 */
   // [self prepareData];
    /** 调用创建tableView */
    [self creatTableView];
    /** 调用图书详情*/
    [self buildBookDetailView];
    self.pageCount = 0;
    [self.tableView.mj_header beginRefreshing];
    [self creatInputView];
    // 注册通知
    [self registerNotification];
}
#pragma mark - 注册的通知
- (void)registerNotification{
    // 点击阅读过此书的人的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(sendMessageToOtherPersonal:) name:@"SendMessageToOtherPersonal" object:nil];
    // 注册通知 监听键盘弹起
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InputCommentViewKeyboardRise:) name:UIKeyboardWillShowNotification object:nil];
    // 监听键盘收回
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(InputCommentViewKeyboardHidden:) name:UIKeyboardWillHideNotification object:nil];
    // 注册通知 回复的时候让键盘弹起
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(replyCommetn) name:@"REPLYCOMMENT" object:nil];
    // 注册通知 接收点击回复者的id
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(transferReplyUserID:) name:@"transferReplyID" object:nil];
    // 注册通知,点击显示全部评论之后 用来更新视图
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(replyCommentUpdate:) name:@"REPLYCOMMENTUPDATE" object:nil];
}
#pragma mark - 点击更多评论后更新视图
- (void)replyCommentUpdate:(NSNotification *)notif{
    NSIndexPath *index = notif.object;
    DAHomePageTimeLineModel *homePageModel = self.dataArray[index.row];
    homePageModel.isReplyCommentAllShow = YES;
    self.dataArray[index.row] = homePageModel;
   // [self.tableView reloadData];
    NSArray *indexArray = [NSArray arrayWithObject:index];
    [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
    NSLog(@"通知");
}
#pragma mark - 创建输入评论的view
- (void)creatInputView{
    self.inputCommentView = [[DAInputCommentView alloc]initWithFrame:CGRectMake(0, SCREENHEIGHT + 40, SCREENWIDTH, 40)];
    self.inputCommentView.sendTextView.scrollsToTop = NO;
    [self.view addSubview:self.inputCommentView];
    __weak typeof(self)weakSelf = self;
    [weakSelf.inputCommentView setContentSizeBlock:^(CGSize contentSize) {
        [weakSelf updateHeight:contentSize];
    }];
    // 注册通知 监听是否点击评论 点击评论键盘弹起
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickComment) name:@"ClickCommentView" object:nil];
    [weakSelf.inputCommentView setReplyAddBlock:^(NSString *replyText, NSInteger inputTag) {
        [weakSelf sendComment: replyText];
    }];
}
- (void)clickComment{
    [self.inputCommentView.sendTextView becomeFirstResponder];
}
- (void)transferReplyUserID:(NSNotification *)notif{
    // 获取到要回复的人的id
    self.replyUserID = notif.object[@"replayUserID"];
    self.replyToUserName = notif.object[@"replayName"];
    self.replyTimeLine = notif.object[@"replytTimeline"];
    self.cellIndexPath = notif.object[@"cellIndexPath"];
    self.selectIndexPath = notif.object[@"cellIndexPath"];
    self.replyToOtherFloat = [notif.object[@"replyHeight"] floatValue];
    self.isBackCellTag = [notif.object[@"isBackCell"] integerValue];
    self.isFlag = NO;
    self.isKeyboardFirstShow = YES;
}
- (void)replyDelegateUserReplyMessage:(NSString *)replyUserID{
    if ([replyUserID isEqualToString:self.userID]) {
        [self.popView dismiss];
        [self alertSheetShow];
        if (self.isShowingKeyboard) {
            [self.inputCommentView.sendTextView resignFirstResponder];
            
        }
    }else{
        if (self.isShowingKeyboard) {
            [self.inputCommentView.sendTextView resignFirstResponder];
            
        }else{
            [self replyToOtherHeight];
            
        }
//        [self.inputCommentView.sendTextView becomeFirstResponder];
//        self.isSelectComment = NO;
    }
}
- (void)replyToOtherHeight{
    if (self.isBackCellTag == 0) {
        DABorrowBookTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.cellIndexPath];
        self.replyHeight = [cell convertRect:cell.bounds toView:self.view.window].origin.y + cell.frame.size.height;
    }else{
        DABackBookTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.cellIndexPath];
        self.replyHeight = [cell convertRect:cell.bounds toView:self.view.window].origin.y + cell.frame.size.height;
    }
    [self.inputCommentView.sendTextView becomeFirstResponder];
    self.isSelectComment = NO;
}
#pragma mark - 删除评论
- (void)alertSheetShow{
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认删除评论吗" preferredStyle:UIAlertControllerStyleActionSheet];
//    UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//    }];
//    UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//    }];
//    [alert addAction:leftAction];
//    [alert addAction:rightAction];
//    [self presentViewController:alert animated:YES completion:nil];
    
}
// 点击评论的cell 通知触发的方法
- (void)replyCommetn{
    [self replyDelegateUserReplyMessage:self.replyUserID];
}
#pragma mark - 发表评论
- (void)sendComment:(NSString *)str{
    NSLog(@"发送评论!!!!");
    [self postReplyMessage:str];
    [self.inputCommentView.sendTextView resignFirstResponder];
}
#pragma mark - 发表评论的网络请求
- (void)postReplyMessage: (NSString *)message{
    NSString *userID = self.userID;
    NSString *replyUserID = self.replyUserID;
    NSString *replyTimeline = [self.dataArray[self.selectIndexPath.row] timelineID];
    NSString *replyContent = message;
    
    DAHomePageTimeLineModel *homePageModel;
    NSIndexPath *index;
    if (self.isSelectComment) {
        self.replyDic = [@{@"userID": userID,
               @"replyTimeline": replyTimeline,
               @"replyContent": replyContent} mutableCopy];
        homePageModel = self.dataArray[self.selectIndexPath.row];
        index = self.selectIndexPath;
    }else{
        self.replyDic = [@{@"userID": userID,
                @"replyTimeline": self.replyTimeLine,
                @"replyContent": replyContent,
                @"replyUserID": replyUserID} mutableCopy];
        homePageModel = self.dataArray[self.cellIndexPath.row];
        index = self.cellIndexPath;
    }
    // 先获取当前timeline的replyArray
    // DAHomePageTimeLineModel *homePageModel = self.dataArray[self.selectIndexPath.row];
    NSMutableArray *array = [NSMutableArray array];
    NSMutableArray *resultArray = [NSMutableArray array];
    [resultArray addObjectsFromArray:homePageModel.replyArray];
    NSString *url = DASendReplyMessageURL;
    __weak typeof(self)weakSelf = self;
    [DADataHandel postURL:url parame:self.replyDic cookie:nil result:^(id result) {
        if ([result[@"result"] isEqualToString:@"true"]) {
            NSLog(@"发表评论成功");            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [weakSelf getUserInfo];
                if (weakSelf.isSelectComment) {
                    [weakSelf.replyDic setValue:weakSelf.userName forKey:@"replyUserName"];
                    NSString *str = [NSString stringWithFormat:@"%@:%@", weakSelf.replyDic[@"replyUserName"], weakSelf.replyDic[@"replyContent"]];
                    CGFloat sum = [weakSelf heightWithText:str Width:[UIScreen mainScreen].bounds.size.width - 120 Font:12];
                    NSLog(@"评论:%f", sum);
                    homePageModel.rowHeight += sum + 10;
                    NSString *sumStr = [NSString stringWithFormat:@"%f", sum];
                    [homePageModel.replyHeightArray addObject:sumStr];
                    if (homePageModel.replyArray.count <= 4) {
                        homePageModel.beforeTenRowHeight += sum + 10;
                    }
                    self.commentTableViewCellRowHeight = sum;
                }else{
                    [weakSelf.replyDic setValue:weakSelf.userName forKey:@"replyUserName"];
                    [weakSelf.replyDic setValue:weakSelf.replyToUserName forKey:@"replyToName"];
                    [weakSelf.replyDic setValue:weakSelf.userID forKey:@"replyID"];
                    [weakSelf.replyDic setValue:weakSelf.replyUserID forKey:@"replyToID"];
                    [weakSelf.replyDic setValue:weakSelf.userID forKey:@"replyUserID"];
                    NSString *str = [NSString stringWithFormat:@"%@回复%@:%@", weakSelf.replyDic[@"replyUserName"], weakSelf.replyDic[@"replyToName"], weakSelf.replyDic[@"replyContent"]];
                    CGFloat width = [UIScreen mainScreen].bounds.size.width - 120;
                    CGFloat sum = [weakSelf heightWithText:str Width:width Font:12];
                    NSLog(@"回复:%f", sum);
                    homePageModel.rowHeight += sum + 10;
                    NSString *sumStr = [NSString stringWithFormat:@"%f",sum];
                    [homePageModel.replyHeightArray addObject:sumStr];
                    if (homePageModel.replyArray.count <= 4) {
                        homePageModel.beforeTenRowHeight += sum + 10;
                    }
                    self.commentTableViewCellRowHeight = sum ;
                    //self.commentTableViewCellRowHeight = sum ;
                }
                [array addObject:weakSelf.replyDic];
                NSMutableArray *modelArray =[DAReplyModel returnModelInArrayWithDic:array];
                DAReplyModel *replyModel = modelArray.lastObject;
                replyModel.rowHeight = self.commentTableViewCellRowHeight;
                [resultArray addObjectsFromArray:modelArray];
                homePageModel.replyArray = resultArray;
                weakSelf.dataArray[index.row] = homePageModel;
                // 回到主线程
                dispatch_async(dispatch_get_main_queue(), ^{
                  //  [weakSelf.tableView reloadData];
                    NSArray *indexArray = [NSArray arrayWithObject:index];
                    [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
                });
            });
        }else{
            NSLog(@"评论失败了");
            NSString *isFail = NSLocalizedString(@"isCommentFail", nil);
            [SVProgressHUD showErrorWithStatus:isFail];
        }
    }];
}
- (void)getUserInfo{
  self.userName = [self readLocalTheUserInfoData];
}
#pragma mark - 键盘弹起
- (void)InputCommentViewKeyboardRise:(NSNotification *)notif{
    NSString *comment = NSLocalizedString(@"comment", nil);
   // NSString *reply = NSLocalizedString(@"reply", nil);
    if (self.isSelectComment) {
        self.inputCommentView.placeHolder.text = comment;
    }else{
       // self.inputCommentView.placeHolder.text = reply;
    }
    [self.backView removeFromSuperview];
    NSLog(@"___%ld", self.selectIndexPath.row);
    CGRect frame =  [[[notif userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect frame2 = [[[notif userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  //  NSLog(@"###%@", NSStringFromCGRect(frame));
    __weak typeof(self) weakSelf = self;
        [UIView animateWithDuration:0.2 animations:^{
            self.inputCommentView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height -frame2.size.height - 40 - 64, self.view.frame.size.width, 40);
            CGRect CommentViewframe = self.inputCommentView.frame;
            CGPoint point = self.tableView.contentOffset;
            NSLog(@"Point:%@", NSStringFromCGPoint(point));
            if (weakSelf.isKeyboardFirstShow) {
                self.currentTableViewPoint = point;
                weakSelf.isFirstRiseFrame = frame;
                if (weakSelf.isFlag) {
                    point.y -= (CommentViewframe.origin.y + 64 - weakSelf.replyViewDrawFloat);
                    weakSelf.tableView.contentOffset = point;
                    weakSelf.isShowingKeyboard = NO;
                }else{
                    point.y -= (CommentViewframe.origin.y + 64 - weakSelf.replyHeight + (weakSelf.replyHeight - weakSelf.replyToOtherFloat));
                    weakSelf.tableView.contentOffset = point;
                }
            }else{
                point.y = point.y + frame.origin.y - frame2.origin.y;
                weakSelf.tableView.contentOffset = point;
                weakSelf.isShowingKeyboard = NO;
            }
        }completion:^(BOOL finished) {
            //[weakSelf crearBackView];
            [weakSelf.view bringSubviewToFront:weakSelf.inputCommentView];
            weakSelf.isKeyboardFirstShow = NO;
            // 键盘已经弹起 标记键盘状态
            weakSelf.isShowingKeyboard  = YES;
        } ];
}
#pragma mark -创建背景透明view
- (void)crearBackView{
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
    self.backView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.backView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ClickBackView)];
    [self.backView addGestureRecognizer:tap];
}
#pragma mark - 键盘收起
- (void)InputCommentViewKeyboardHidden:(NSNotification *)notif{
    self.isKeyboardFirstShow = YES;
    [self.popView dismiss];
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.inputCommentView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height + 40, [UIScreen mainScreen].bounds.size.width, 40);
        // 判断是6Plus 设备
//        if ([UIScreen mainScreen].bounds.size.height == 736 ) {
//            if (self.selectIndexPath.row <= 2) {
//                weakSelf.tableView.contentOffset = weakSelf.currentTableViewPoint;
//            }
//        }else{
//            if (self.selectIndexPath.row == 0 || self.selectIndexPath.row == 1 || self.selectIndexPath.row
//                == self.dataArray.count - 1) {
//                weakSelf.tableView.contentOffset = weakSelf.currentTableViewPoint;
//            }
//            
//        }
        weakSelf.tableView.contentOffset = weakSelf.currentTableViewPoint;

        
    } completion:^(BOOL finished) {
        // [weakSelf.backView removeFromSuperview];
        weakSelf.backCell.isSelectLikeAndCommentView = YES;
        // 置空输入框里的文字
        weakSelf.inputCommentView.sendTextView.text = nil;
       //  self.inputCommentView.placeHolder.text = @"评论";
        // 键盘已经收回  标记键盘状态
        weakSelf.isShowingKeyboard  = NO;
    }];
}
#pragma mark - 键盘弹起之后后面铺设一个背景view 
// 背景view点击方法
- (void)ClickBackView{
    [self.inputCommentView.sendTextView resignFirstResponder];
    [self.popView dismiss];
    [self.backView removeFromSuperview];
}
#pragma mark - 更新replyView的高度约束
- (void)updateHeight:(CGSize)contentSize{
    CGFloat contentSizeHeight = contentSize.height;
    // 设置最大不能超过100
    if (contentSize.height > 100) {
        contentSizeHeight = 100;
    }
    float height = contentSizeHeight + 10;
    CGRect frame = self.inputCommentView.frame;
    frame.origin.y -= height - frame.size.height;
    frame.size.height = height;
    self.inputCommentView.frame = frame;
}
#pragma mark - 导航栏设置
- (void)ConfigurationNavigation{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Timeline" style:UIBarButtonItemStylePlain target:self action:@selector(clickTimeLine)];
   self.navigationItem.leftBarButtonItem.enabled = NO;
    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName,[UIColor whiteColor],NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
  //  UIImage *image = [UIImage imageNamed:@"searchUser"];
  //  image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  //  self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(clickTimeLine)];
    //self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"searchUser"] style:UIBarButtonItemStylePlain target:self action:@selector(clickTimeLine)];
}
#pragma mark- 点击搜索按钮
- (void)clickSearchBook{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    DABookTypeViewController *bookType = [story instantiateViewControllerWithIdentifier:@"BOOKTYPE"];
    bookType.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:bookType animated:YES];
}
#pragma mark - 点击timeLine
- (void)clickTimeLine{
    DAUserListViewController *user = [self.storyboard instantiateViewControllerWithIdentifier:@"USERLIST"];
    user.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:user animated:YES];
}
#pragma mark - 创建tableView
- (void)creatTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tabBarController.tabBar.translucent = YES;
//    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    // 刷新头部
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld@3x", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld@3x", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21@3x"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer.hidden = YES;
}
#pragma mark - 下拉刷新
- (void)refreshData{
    self.isRefresh = YES;
    self.pageCount = 0;
    [self prepareHomePageTimeline];
}
#pragma mark - 上拉
- (void)loadMoreData{
    self.isRefresh = NO;
    [self prepareHomePageTimeline];
}
// ================================网络请求和数据处理========================================//
#pragma mark - 准备数据
- (void)prepareHomePageTimeline{
    NSString *url = DAHomePageTimeLineURL;
    NSString *pageNumber = [NSString stringWithFormat:@"%ld", (long)self.pageCount];
    NSDictionary *dic = @{@"page": pageNumber};
    NSLog(@"%ld", (long)self.pageCount);
    [self dataHandelWithUrl:url parame:dic];
}
#pragma mark - 网络请求
- (void)dataHandelWithUrl:(NSString *)url parame:(NSDictionary *)dic{
     __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        // 调用开辟的线程处理数据
        if (result) {
            if (self.isRefresh) {
                [self.tableView.mj_header endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }
        [weakSelf creatThreadForData:result];
    }];
}
#pragma mark - 网络数据回来之后的数据处理/或者存到本地的数据处理
- (void)dataTransformModel:(NSArray *)dataArray{
    DAHomePageTimeLineModel *timeLineModel = [[DAHomePageTimeLineModel alloc]init];
    NSArray *array = [timeLineModel returnModelInArrayWithDic:dataArray];
    if (self.isRefresh) {
        self.dataArray = [NSMutableArray array];
        [self.dataArray addObjectsFromArray:array];
       // [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }else{
        [self.dataArray addObjectsFromArray:array];
       // [self.tableView reloadData];
         [self.tableView.mj_footer endRefreshing];
    }
   // [self finishLoadDataMBProgress];
    [self calculateReplyHeight:self.dataArray];
}
#pragma mark 开辟线程处理数据
- (void)creatThreadForData:(id)result{
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [weakSelf.tableView.mj_header endRefreshing];
        if ([result[@"result"] isKindOfClass:[NSArray class]]) {
            if ([result[@"result"] count] > 0) {
                if ([result[@"result"] count] < 20) {
                    weakSelf.tableView.mj_footer.hidden = YES;
                }else{
                    weakSelf.tableView.mj_footer.hidden = NO;
                }
                // 数据处理
                [weakSelf dataTransformModel:result[@"result"]];
                weakSelf.pageCount++;
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            // [self finishLoadDataMBProgress];
        }else{
            NSLog(@"请求数据失败");
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
                [weakSelf.tableView.mj_header endRefreshing];
            }
            else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }
        // 回到主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            if (self.isRefresh) {
                [self.tableView.mj_header endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        });
    
    });
}
#pragma mark - 计算高度
- (void)calculateReplyHeight:(NSArray *)array{
    if (self.isRefresh) {
        [self.tableView.mj_header endRefreshing];
    }else{
        [self.tableView.mj_footer endRefreshing];
    }
    CGFloat sum = 0;
    CGFloat beforeTenRowHeight = 0;
    NSString *message;
    NSString *replyUserName;
    NSString *replyToName;
    NSString *content;
    NSInteger count = 0;
    for (DAHomePageTimeLineModel *model in array) {
        sum = 0;
        count = 0;
        beforeTenRowHeight = 0;
        model.replyHeightArray = [NSMutableArray array];
        NSMutableArray *array =  [DAReplyModel returnModelInArrayWithDic:model.replyArray];
        for (DAReplyModel *replyModel in array) {
            message = replyModel.replyContent;
            replyUserName = replyModel.replyUserName;
            replyToName = replyModel.replyToName;
            if ([replyToName isKindOfClass:[NSNull class]] || replyToName == nil) {
                content = [NSString stringWithFormat:@"%@:%@", replyUserName, message];
            }else{
                if (replyUserName != nil && replyToName != nil) {
                    NSString *reply = NSLocalizedString(@"reply", nil);
                    content = [NSString stringWithFormat:@"%@%@%@:%@", replyUserName, reply,replyToName, message];
                }
            }
            if (model.replyArray.count > 0) {
                CGFloat sumHeight = [self heightWithText:content Width:[UIScreen mainScreen].bounds.size.width - 120 Font:12];
                sum += sumHeight + 10;
                if (count < 5) {
                    beforeTenRowHeight += sumHeight + 10;
                }
                model.rowHeight = sum;
                model.beforeTenRowHeight = beforeTenRowHeight;
                NSString *heightStr = [NSString stringWithFormat:@"%f", sumHeight];
                [model.replyHeightArray addObject:heightStr];
                replyModel.rowHeight = sumHeight;
                model.replyArray = array;
                // 默认不全显示
                model.isReplyCommentAllShow = NO;
            }else{
                model.rowHeight = 0;
            }
            count++;
        }
    }
//    // 回到主线程刷新
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if (self.isRefresh) {
//            [self.tableView.mj_header endRefreshing];
//        }else{
//            [self.tableView.mj_footer endRefreshing];
//        }
//        [self.tableView reloadData];
//    });
}
//====================================结束======================================================//
#pragma mark - tableView协议方法 (调整cell的分割线左间距)
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 75, 0, 0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 75, 0, 0)];
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        // "2" 代表 还书
        if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"2"]) {
            DABackBookTableViewCell *backCell = [tableView dequeueReusableCellWithIdentifier:@"back"];
            if (backCell == nil) {
                backCell = [[DABackBookTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"back"];
            }
                backCell.cellIndexPath = indexPath;
                backCell.timelineModel = self.dataArray[indexPath.row];
                backCell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
                backCell.selectionStyle = UITableViewCellSelectionStyleNone;
                // 设置代理人
                backCell.delegate = self;
                //  backCell.commentArray = [self.dataArray[indexPath.row] replyArray];
                [backCell.CommentButton addTarget:self action:@selector(clickCommentButton:) forControlEvents:UIControlEventTouchUpInside];
                backCell.CommentButton.appendIndexPath = indexPath;
                backCell.CommentButton.selectIndex = indexPath.row;
                backCell.CommentButton.isBack = YES;
                backCell.commentView.timeLineID = [self.dataArray[indexPath.row] timelineID];
                backCell.commentView.isBackCell = 1;
            return backCell;
        }
        // "1" 代表 借书
        else if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"1"]){
            DABorrowBookTableViewCell *borrowCell = [tableView dequeueReusableCellWithIdentifier:@"borrow"];
            if (borrowCell == nil) {
                borrowCell = [[DABorrowBookTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"borrow"];
            }
            borrowCell.borrowCellIndexPath = indexPath;
            borrowCell.timelineModel = self.dataArray[indexPath.row];
            borrowCell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
            borrowCell.delegate = self;
            borrowCell.selectionStyle = UITableViewCellSelectionStyleNone;
          //  borrowCell.commentArray = [self.dataArray[indexPath.row] replyArray];
            [borrowCell.DACommentButton addTarget:self action:@selector(clickCommentButton:) forControlEvents:UIControlEventTouchUpInside];
            borrowCell.DACommentButton.appendIndexPath = indexPath;
            borrowCell.DACommentButton.selectIndex = indexPath.row;
            borrowCell.DACommentButton.isBack = NO;
            borrowCell.commentView.timeLineID = [self.dataArray[indexPath.row] timelineID];
            borrowCell.commentView.isBackCell = 0;
            return borrowCell;
        } // "3" 代表 上传文件
        else if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"3"]){
            DAFileUploadTableViewCell *fileUploadCell = [tableView dequeueReusableCellWithIdentifier:@"fileUpload"];
            if (fileUploadCell == nil) {
                fileUploadCell = [[DAFileUploadTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"fileUpload"];
            }
            fileUploadCell.cellIndexPath = indexPath;
            fileUploadCell.model = self.dataArray[indexPath.row];
            fileUploadCell.backgroundColor = [UIColor colorWithHexString:backGroundColor];
            fileUploadCell.selectionStyle = UITableViewCellSelectionStyleNone;
            fileUploadCell.commentView.timeLineID = [self.dataArray[indexPath.row] timelineID];
            [fileUploadCell.DACommentButton addTarget:self action:@selector(clickCommentButton:) forControlEvents:UIControlEventTouchUpInside];
            fileUploadCell.DACommentButton.appendIndexPath = indexPath;
            fileUploadCell.delegate = self;
            return fileUploadCell;
        }
        else{
            // 0 代表 系统
            DASystemNotificationTableViewCell *system = [tableView dequeueReusableCellWithIdentifier:@"system"];
            if (system == nil) {
                system = [[DASystemNotificationTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"system"];
            }
            system.timeLineModel = self.dataArray[indexPath.row];
            system.backgroundColor = [UIColor colorWithHexString:backGroundColor];
            system.selectionStyle = UITableViewCellSelectionStyleNone;
            return system;
        }
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"1"]) {
        CGFloat sum = [self.dataArray[indexPath.row] beforeTenRowHeight];
        if ([self.dataArray[indexPath.row] replyArray].count > 0) {
            if ([self.dataArray[indexPath.row] isReplyCommentAllShow]) {
                CGFloat rowHeight = [self.dataArray[indexPath.row] rowHeight];
                return 145 + rowHeight + 10;
            }
            if ([self.dataArray[indexPath.row] replyArray].count <= 5) {
                return 145 + sum + 10;
            }
            return 145 + sum + 10 + 30 + 0.5;
        }else{
            return 145 + sum + 10;
        }
    }
    else  if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"2"]) {
        CGFloat textHeight = [self heightWithText:[self.dataArray[indexPath.row] rateMessage] Width:[UIScreen mainScreen].bounds.size.width - 144 Font:12];
        CGFloat BackSum = [self.dataArray[indexPath.row] beforeTenRowHeight];
        if ([self.dataArray[indexPath.row] replyArray].count > 0) {
            if ([self.dataArray[indexPath.row] isReplyCommentAllShow]) {
                CGFloat rowHeight = [self.dataArray[indexPath.row] rowHeight];
                return 130 + textHeight + 48 + rowHeight + 10;
            }
            if ([[self.dataArray[indexPath.row] replyArray] count] <= 5) {
                return 130 + textHeight + 48 +BackSum + 10;
            }
            return 130 + textHeight + 48 + BackSum + 10 + 30 + 0.5;
        }else{
            return 130 + textHeight + 48 + BackSum + 10;
        }
    }
    else if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"3"]){
        CGFloat sum = [self.dataArray[indexPath.row] beforeTenRowHeight];
        if ([self.dataArray[indexPath.row] replyArray].count > 0) {
            if ([self.dataArray[indexPath.row] isReplyCommentAllShow]) {
                CGFloat rowHeight = [self.dataArray[indexPath.row] rowHeight];
                return 100 + rowHeight + 15;
            }
            if ([self.dataArray[indexPath.row] replyArray].count <= 5) {
                return 100 + sum + 10;
            }
            return 100 + sum + 10 + 30 + 0.5;
        }else{
            return 100 + sum + 10;
        }
    }
    else{
        //** 根据label 的内容 计算文字高度 */
        CGFloat labelHeight = [self heightWithText:[self.dataArray[indexPath.row] timelineMessage] Width:[UIScreen mainScreen].bounds.size.width - 100 Font:12];
        return 40 + labelHeight + 16;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"1"]) {
        CGFloat sum = [self.dataArray[indexPath.row] beforeTenRowHeight];
        if ([self.dataArray[indexPath.row] replyArray].count > 0) {
            if ([self.dataArray[indexPath.row] isReplyCommentAllShow]) {
                CGFloat rowHeight = [self.dataArray[indexPath.row] rowHeight];
                return 145 + rowHeight + 10;
            }
            if ([self.dataArray[indexPath.row] replyArray].count <= 5) {
                return 145 + sum + 10;
            }
            return 145 + sum + 10 + 30 + 0.5;
        }else{
            return 145 + sum + 10;
        }
    }
  else  if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"2"]) {
      CGFloat textHeight = [self heightWithText:[self.dataArray[indexPath.row] rateMessage] Width:[UIScreen mainScreen].bounds.size.width - 144 Font:12];
      CGFloat BackSum = [self.dataArray[indexPath.row] beforeTenRowHeight];
      if ([self.dataArray[indexPath.row] replyArray].count > 0) {
          if ([self.dataArray[indexPath.row] isReplyCommentAllShow]) {
              CGFloat rowHeight = [self.dataArray[indexPath.row] rowHeight];
              return 130 + textHeight + 48 + rowHeight + 10;
          }
          if ([[self.dataArray[indexPath.row] replyArray] count] <= 5) {
              return 130 + textHeight + 48 +BackSum + 10;
          }
          return 130 + textHeight + 48 + BackSum + 10 + 30 + 0.5;
      }else{
          return 130 + textHeight + 48 + BackSum + 10;
      }
  }else if ([[self.dataArray[indexPath.row] timelineType] isEqualToString:@"3"]){
      CGFloat sum = [self.dataArray[indexPath.row] beforeTenRowHeight];
      if ([self.dataArray[indexPath.row] replyArray].count > 0) {
          if ([self.dataArray[indexPath.row] isReplyCommentAllShow]) {
              CGFloat rowHeight = [self.dataArray[indexPath.row] rowHeight];
              return 100 + rowHeight + 20;
          }
          if ([self.dataArray[indexPath.row] replyArray].count <= 5) {
              return 100 + sum + 10;
          }
          return 100 + sum + 10 + 30 + 0.5;
      }else{
          return 100 + sum + 10;
      }
  }
    else{
        //** 根据label 的内容 计算文字高度 */
       // CGFloat  Labelheight = [self heightWithText:[self.dataArray[indexPath.row] timelineMessage]];
        CGFloat labelHeight = [self heightWithText:[self.dataArray[indexPath.row] timelineMessage] Width:[UIScreen mainScreen].bounds.size.width - 100 Font:12];
        return 40 + labelHeight + 16;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.popView dismiss];
    // 点击cell 时 输入框消失
    [self.inputCommentView.sendTextView resignFirstResponder];
}
#pragma mark - DACommentButton的点击方法
- (void)clickCommentButton:(DACommentButton *)sender {
    // 创建背景透明view
   // [self crearBackView];
    // 根据DACommentButon的isBack的属性 判断点击的是哪个类型的cell
    if (sender.isBack) {
       DABackBookTableViewCell *backCell = (DABackBookTableViewCell *)sender.superview.superview;
        self.replyViewDrawFloat = [backCell convertRect:backCell.bounds toView:self.view.window].origin.y + backCell.frame.size.height;
    }else{
        DABorrowBookTableViewCell *borrowCell = (DABorrowBookTableViewCell *)sender.superview.superview;
        self.replyViewDrawFloat = [borrowCell convertRect:borrowCell.bounds toView:self.view.window].origin.y + borrowCell.frame.size.height;
    }
    self.isFlag = YES;
    NSString *comment = NSLocalizedString(@"comment", nil);
    self.inputCommentView.placeHolder.text = comment;
//    CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:sender.appendIndexPath];
//    CGFloat origin_y = rectInTableView.origin.y + sender.frame.origin.y;
//    CGRect targetRect = CGRectMake(CGRectGetMinX(sender.frame), origin_y, CGRectGetWidth(sender.bounds), CGRectGetHeight(sender.bounds));
//    if (self.popView.shouldShowed) {
//        [self.popView dismiss];
//        return;
//    }
    // 记录点击的indexPath
    self.selectIndexPath = sender.appendIndexPath;
    self.index = sender.selectIndex;
   // [self.popView showAtView:self.tableView rect:targetRect isFavour:NO];
    // 此时点击的是评论
    self.isSelectComment = YES;
    [self.rowsArray removeAllObjects];
    [self.rowsArray addObject:self.selectIndexPath];
    self.isKeyboardFirstShow = YES;
    // 让输入框成为第一响应者 弹起
    [self.inputCommentView.sendTextView becomeFirstResponder];
}
#pragma mark - 评论和点赞按钮
- (DAPopLikeAndCommentView *)popView{
    if (!_popView) {
        _popView = [DAPopLikeAndCommentView initailzerDAOperationView];
        __weak typeof(self)weakSelf = self;
        _popView.didSelectedOperationCompletion = ^(DAOperationType operationType){
            switch (operationType) {
                case DAOperationTypeLike:
                    // 调用点赞方法
                    NSLog(@"赞");
                    break;
                case DAOperationTypeReply:
                    // 调用评论方法
                    NSLog(@"评论");
                    //[self.inputCommentView.sendTextView becomeFirstResponder];
                    [weakSelf.inputCommentView.sendTextView becomeFirstResponder];
                    break;
                default:
                    break;
            }
            
        };
    }
    return _popView;
}
#pragma mark - 滚动的时候评论按钮消失
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.popView dismiss];

}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (self.isShowingKeyboard) {
        [self.inputCommentView.sendTextView resignFirstResponder];
    }
    
}

#pragma mark - 计算文本高度
- (CGFloat)heightWithText:(NSString *)text {
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
    CGSize size = CGSizeMake(300, 1000);
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    /** 返回得到的高度 */
    return rect.size.height;
}
#pragma mark -showBookDetail协议方法
- (void)showBookDetail:(NSString *)bookID{
    self.detailView.bookID = bookID;
    self.detailView.isSelectHomePageTimeLine = YES;
    self.detailView.isSelectPersonalPage = NO;
    self.detailView.isSelectOtherPersonalPage = NO;
    [self.detailView prepareData];
    [self showGrayView];
    [self creatBookDetailView];
    [self.detailView.scrollView setContentOffset:CGPointMake(0, 0)];
}
#pragma mark - borrowBookShowDetail协议方法
- (void)borrowBookShowDetail:(NSString *)bookID{
    [self showGrayView];
    [self creatBookDetailView];
    self.detailView.bookID = bookID;
    self.detailView.isSelectHomePageTimeLine = YES;
    self.detailView.isSelectPersonalPage = NO;
    self.detailView.isSelectOtherPersonalPage = NO;
    [self.detailView prepareData];
    [self.detailView.scrollView setContentOffset:CGPointMake(0, 0)];
}
#pragma mark - 弹出灰色蒙版
- (void)showGrayView{
    /** 灰色蒙版*/
    self.grayView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.grayView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:self.grayView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickClose:)];
    [self.grayView addGestureRecognizer:tap];
}
- (void)grayViewHidden{
    [self.grayView removeFromSuperview];
}
#pragma mark - 弹出的图书详情页面
- (void)buildBookDetailView{
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewHidden:) name:@"VIEWHIDDEN" object:nil];
    self.detailView = [self.storyboard instantiateViewControllerWithIdentifier:@"BOOKDETAIL"];
    self.detailView.view.frame = CGRectMake(20, 80, self.view.frame.size.width - 40, 400 * HEIGHTTOFIT5s);
    [[UIApplication sharedApplication].keyWindow addSubview:self.detailView.view];
    self.detailView.view.hidden = YES;
}
#pragma mark - 创建首页book的详情页
- (void)creatBookDetailView{
   // self.detailView.view.hidden = NO;
    [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self.detailView.view];
    /** 添加动画*/
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.detailView.view cache:YES];
    [UIView commitAnimations];
    
//    self.detailView.view.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
//    self.detailView.view.alpha = 0.0f;
//    [UIView animateWithDuration:0.1f animations:^{
//        self.detailView.view.transform = CGAffineTransformMakeScale(1.1f, 1.1f);
//        self.detailView.view.alpha = 1.0f;
//    } completion:^(BOOL finished) {
//        [UIView animateWithDuration:0.1f animations:^{
//            self.detailView.view.transform = CGAffineTransformMakeScale(0.9f, 0.9f);
//        } completion:^(BOOL finished) {
//           [UIView animateWithDuration:0.2f animations:^{
//               self.detailView.view.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
//           } completion:nil];
//        }];
//    }];
    /** 消失手势*/
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickClose:)];
   // [self.detailView.closeImage addGestureRecognizer:tap];
    [self.detailView.closeImageBackView addGestureRecognizer:tap];
    /** bookImage手势*/
    UITapGestureRecognizer *bookImageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickBookImage:)];
    self.detailView.bookImage.userInteractionEnabled = YES;
    //self.detailView.closeImageBackView.userInteractionEnabled = YES;
    [self.detailView.bookImage addGestureRecognizer:bookImageTap];
}
-(void)viewHidden:(NSNotificationCenter *)not{
    self.detailView.view.hidden = NO;
}
#pragma mark - 点击closeImage触发的方法
- (void)clickClose:(UITapGestureRecognizer *)tap{
    NSLog(@"关闭");
    self.detailView.view.hidden = YES;
    [self.grayView removeFromSuperview];
}
#pragma mark - 点击bookImage触发的方法
- (void)clickBookImage:(UITapGestureRecognizer *)tap{
    /** 跳转到图书详情页面*/
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    DASearchBookDetailViewController *detailVC = [story instantiateViewControllerWithIdentifier:@"SEARCHBOOKDETAIL"];
    detailVC.bookID = self.detailView.bookID;
    [self clickClose:nil];
    detailVC.hidesBottomBarWhenPushed = YES;
    detailVC.isHomePageEnter = YES;
   // [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
   // [SVProgressHUD showWithStatus:@"正在加载"];
   //[detailVC prepareData];
    /** 转场动画
     *CTransition *transition = [CATransition animation];
     *transition.duration = 1.0f;
     *transition.type = @"rippleEffect";
     *transition.subtype = kCATransitionFromTop;
     *[self.navigationController.view.layer addAnimation:transition forKey:nil];
    */
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - 点击头像跳转到个人页面的协议方法
- (void)borrowCellTurnPersonalPageWithUserID:(NSString *)userId{
    [self turnPersonal:userId];
}
- (void)backCellTurnPersonalPageWithUserID:(NSString *)userId{
    [self turnPersonal:userId];
}
- (void)clickFileUserFaceImageWith:(DAHomePageTimeLineModel *)model{
    [self turnPersonal:model.userID];
}
#pragma mark - 跳转到其他个人页面
- (void)turnPersonal:(NSString *)userID{
    DAOtherPersonalViewController *otherPersonal = [self.storyboard instantiateViewControllerWithIdentifier:@"OTHERPERSONAL"];
    otherPersonal.hidesBottomBarWhenPushed = YES;
    otherPersonal.otherUserID = userID;
    [self.navigationController pushViewController:otherPersonal animated:YES];
}

#pragma mark - 点击上传文件的图片 协议方法
- (void)clickFileImageWithModel:(DAHomePageTimeLineModel *)model{
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.timelinefolderName,model.timelinefileExtend];
    NSLog(@"文件保存路径 %@",documentsDirectory);
    DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
    webFile.fileUrl = filePath;
    webFile.fileID = model.fileID;
    webFile.filefolderName = model.timelinefolderName;
    webFile.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webFile animated:YES];
}

#pragma mark - 判断沙盒里是否有这个文件
-(BOOL)isFileExist:(NSString *)fileName inPath:(NSString *)path{
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    //  NSLog(@"该文件：%@",result?@"有！！":@"不存在");
    return result;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    NSLog(@"首页 memory Warning");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
